package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"mygoedu/day11/socket"
	"net"
	"strconv"
	"time"
)

func main() {
	ip := "127.0.0.1"
	port := 8080

	addr, err := net.ResolveTCPAddr("tcp", ip+":"+strconv.Itoa(port))
	socket.CheckError(err)

	conn, err := net.DialTCP("tcp", nil, addr)
	socket.CheckError(err)
	defer conn.Close()

	rand.Seed(time.Now().Unix())
	for {
		request := socket.Request{
			A: rand.Intn(100),
			B: rand.Intn(100),
		}
		requestBytes, _ := json.Marshal(request)
		_, err := conn.Write(requestBytes)
		socket.CheckError(err)

		responseBytes := make([]byte, 256)
		readLen, err := conn.Read(responseBytes)
		socket.CheckError(err)

		var response socket.Response
		json.Unmarshal(responseBytes[0:readLen], &response)
		fmt.Printf("sum: %d\n", response.Sum)
		time.Sleep(1 * time.Second)
	}

}
